var layer = layui.layer //弹层
    ,table = layui.table //表格
    ,form = layui.form,$ = layui.jquery,laydate = layui.laydate;
lay('.starttime').each(function(){
    laydate.render({
        elem: this
    });
});
//是否有 工厂统计及费用方式 权限，如果有标签赋值true 并设置不显示
let factoryStatisticsCost=false;
factory_statistics_cost();

//工厂财务标签 有该标签:false 无该标签:true
let isFactoryFinance = true;
isFactoryFinance = getAllRolesByCurr("GCCWYF001");

function getAllJson(jsons) {
    let tmpitem=[]
    for (let item of jsons) {
        let tmparr={}
        tmparr["value"]=item["code"];
        tmparr["name"]=item["name"];
        if(item["users"]){
            for(let it of item["users"]){
                item["list"].push(it)
            }
        }
        if(item["list"] && item["list"].length){
            tmparr["children"]=   this.getAllJson(item["list"]);
            tmpitem.push(tmparr)
        }else{
            tmpitem.push(tmparr)
        }

    }
    return tmpitem
}
function getxmselect(el,name, data) {
    return xmSelect.render({
        el: el,
        name: name,
        tree: {
            show: true,
            showLine: true,
            showFolderIcon:true,
            indent: 20,
            expandedKeys:false
        },
        height: 'auto',
        data: data,
        on: function ({ arr, change, isAdd }) {
            return this
        }
    })
}
let operationList=[];
let deptOperationList=[];
(function () {
    let treeList = getCurrentDepartmentUser();
    if(treeList && treeList.list){
        let operationTree = getAllJson(treeList.list);
        operationList=getxmselect("#operationCode","operationCode", operationTree)
    }else {
        operationList=getxmselect("#operationCode","operationCode", [{name: user.name, value: user.code}])
    }
    //获取当前用户所属部门树()
    let currentDeptTreeList = getAllUserDepartmentTree();
    if (currentDeptTreeList && currentDeptTreeList.list) {
        let deptTree = getAllJson(currentDeptTreeList.list);
        deptOperationList = getxmselect("#deptOperationCode", "deptOperationCode", deptTree);
    } else {
        deptOperationList = getxmselect("#deptOperationCode", "deptOperationCode", [{name: user.name, value: user.code}]);
    }
})()



var data1=[];
layui.use(['dropdown'], function () {
    let dropdown = layui.dropdown;
    dropdown.onFilter("costStatistics", function (event) {
        switch (event) {
            case "s1":
                parent.intab("views/jsp/Money/tpl/costStatistics1.jsp","费用明细统计")
                break
            case "s2":
                parent.intab("views/jsp/Money/tpl/costStatistics2.jsp","费用支付统计")
                break
        }
    });
})

let loginUserCode;
let isMsn="否";
let isFinance="否"
layer.ready(function () {
    $.ajax({
        url:"cost/getAllBillCompany",
        success:function(data){
            if(data.status == 200){
                for(let i in data.data){
                    if (!isEmpty(data.data[i])){
                        $('#billCompanyCode').append(new Option(data.data[i].companyName, data.data[i].companyCode));
                    }
                }
                form.render('select');
            }
        }
    });
    $.ajax({
        url: 'billChange/isMsn',
        type: 'GET',
        async: false, // 同步
        success: function (date) {
            isMsn=date.data
        }
    })
    $.ajax({
        url: 'cost/isFinance',
        type: 'GET',
        async: false, // 同步
        success: function (date) {
            isFinance=date.data
        }
    })
});
form.render();//表单刷新
document.getElementById('clear').onclick = function(){
    operationList.setValue([ ]);
    deptOperationList.setValue([ ]);
};

table.render({
    elem: '#maininformation'
    ,url:'cost/getCostResListByPage'
    ,where:{operationCode : user.code}
    ,toolbar: '#maininformationtoolbar'
    ,totalRow: true
    ,cols: [[
        {checkbox: true, fixed: true, totalRowText: '合计'}
        ,{field:'status', title:'单据类型',sort:true,width: 120,templet:function(d){
                switch (d.status) {
                    case 1: return '草稿箱';
                    case 2: return '待批箱';
                    case 3: return '已批箱';
                    case 4: return '完成箱';
                    case 5: return '垃圾箱';
                }
            }}
        ,{field:'operatorName', title:'操作员',sort:true,width: 120}
        ,{field:'createTime', title:'登记日期',sort:true,width: 120,templet: "<div>{{layui.util.toDateString(d.createTime, 'yyyy-MM-dd')}}</div>"}
        ,{field:'code', title:'登记编号',sort:true,width: 200,event: "registrationnumber"}
        ,{field:'costType', title:'费用类型',sort:true,width: 120,templet: function (d) {
                if (d.costType==1){
                    return '直接费用';
                }else if (d.costType==2){
                    return "间接费用";
                }
            }}
        ,{field:'invoiceCode', title:'发票号码',sort:true,width: 120}
        ,{field:'exportContractCode', title:'外销合同号',sort:true,width: 120}
        ,{field:'stockCode', title:'采购合同号',sort:true,width: 120}
        ,{field:'payeeName', title:'收款单位',sort:true,width: 120}
        ,{field:'totalAmount', title:'费用总金额',sort:true,width: 120, totalRow: true}
        ,{field:'totalCost', title:'实付金额',sort:true,width: 120, totalRow: true}
        ,{field:'totalCostCreateTimeStr', title:'费用实付日期',sort:true,width: 120}
        ,{field:'currencyName', title:'币种',sort:true,width: 120}
        ,{field:'rmbRate', title:'人民币汇率',sort:true,width: 120}
        ,{field:'usdRate', title:'美金汇率',sort:true,width: 120}
        ,{field:'bankName', title:'银行名称',sort:true,width: 120}
        ,{field:'bankAccount', title:'银行账号',sort:true,width: 120}
        ,{field:'accountName', title:'账号名称',sort:true,width: 120}
        ,{field:'billCompanyName', title:'制单公司',sort:true,width: 120}
        ,{field:'description', title:'备注',sort:true,width: 120}
        // ,{field:'amountSplit', title:'已拆分金额',sort:true,width: 120, totalRow: true}
        // ,{field:'undividedAmount', title:'未拆分金额',sort:true,width: 120, totalRow: true}
        // ,{fixed: 'right', width:365, toolbar: '#maininformationeditor', title:'操作'}
        ,{fixed: 'right', width:240, title:'操作',templet: function(d){
                // 单据状态/类型（1：草稿箱，2：待批箱，3：已批箱，4：完成箱，5垃圾箱）
                if(isMsn=="是"){
                    var html="<div>"
                    if(d.status==1 || d.status==2){
                        html=html+"<a class=\"layui-btn layui-btn-sm layui-btn-normal\" lay-event=\"update\">修改</a>";
                    }
                    if(d.status==1){
                        html=html+"<a class=\"layui-btn layui-btn-sm layui-btn-normal\" lay-event=\"submits\">提交审批</a>" +
                            "<a class=\"layui-btn layui-btn-sm layui-btn-normal\" lay-event=\"delete\">删除</a>"
                    }

                    if(d.status==2){
                        html=html+"<a class=\"layui-btn layui-btn-sm layui-btn-normal\" lay-event=\"backtothe\">审批退回</a>" +
                            "<a class=\"layui-btn layui-btn-sm layui-btn-normal\" lay-event=\"through\">审批通过</a>"
                    }
                    if(d.status==3){
                        html=html+"<a class=\"layui-btn layui-btn-sm layui-btn-normal\" lay-event=\"complete\">完成</a>" +
                            "<a class=\"layui-btn layui-btn-sm layui-btn-normal\" lay-event=\"backtothe\">审批退回</a>"
                        if(isFinance=="是" || !isFactoryFinance){
                            html=html+"<a class=\"layui-btn layui-btn-sm layui-btn-normal\" lay-event=\"feepayment\">安排付款</a>"
                        }

                    }
                    if(d.status==4){
                        if(isFinance=="是" || !isFactoryFinance){
                            html=html+"<a class=\"layui-btn layui-btn-sm layui-btn-normal\" lay-event=\"completeBacktothe\">完成退回</a>"
                        }
                    }
                    if(d.status==5){
                        html=html+"<a class=\"layui-btn layui-btn-sm layui-btn-normal\" lay-event=\"delectYes\">彻底删除</a>" +
                            "<a class=\"layui-btn layui-btn-sm layui-btn-normal\" lay-event=\"reduction\">还原</a>"
                    }
                    return html+"</div>";
                }else {
                    var html = "<div>"
                    if (d.status == 1) {
                        html = html + "<a class=\"layui-btn layui-btn-sm layui-btn-normal\" lay-event=\"update\">修改</a>" +
                            "<a class=\"layui-btn layui-btn-sm layui-btn-normal\" lay-event=\"submits\">提交审批</a>" +
                            "<a class=\"layui-btn layui-btn-sm layui-btn-normal\" lay-event=\"delete\">删除</a>";
                    }

                    if(d.status==2){
                        html=html+"<a class=\"layui-btn layui-btn-sm layui-btn-normal\" lay-event=\"backtothe\">审批退回</a>"
                    }
                    if(d.status==3){
                        html=html+"<a class=\"layui-btn layui-btn-sm layui-btn-normal\" lay-event=\"complete\">完成</a>"
                    }
                    if(d.status==5){
                        html=html+"<a class=\"layui-btn layui-btn-sm layui-btn-normal\" lay-event=\"delectYes\">彻底删除</a>" +
                            "<a class=\"layui-btn layui-btn-sm layui-btn-normal\" lay-event=\"reduction\">还原</a>"
                    }
                    return html + "</div>";
                }
            }}
    ]]
    ,id: 'maininformationtableid'
    ,height: $(document).height() - $('#maininformation').offset().top - 75,
    page: true,
    limit: 50,
    limits: [50,100,200,300,500,600,900],
    done: function(){
        //table 显示中文名称
        //1：草稿箱，2：待批箱，3：已批箱，4：完成箱，5垃圾箱
        $("[data-field='status']").children().each(function(){
            if($(this).text()=='1'){
                $(this).text("草稿箱")
            }else if($(this).text()=='2'){
                $(this).text("待批箱")
            }else if($(this).text()=='3'){
                $(this).text("已批箱")
            }else if($(this).text()=='4'){
                $(this).text("完成箱")
            }else if($(this).text()=='5'){
                $(this).text("垃圾箱")
            }
        })
        //table显示中文名称。1：直接费用，2：间接费用
        $("[data-field='costType']").children().each(function(){
            if($(this).text()=='1'){
                $(this).text("直接费用")
            }else if($(this).text()=='2'){
                $(this).text("间接费用")
            }
        })
    }
});

//监听复选框
table.on('checkbox(maininformationtable)', function (data) {
    var checkStatus = table.checkStatus("maininformationtableid").data;
    for(var i = 0;i<checkStatus.length;i++){
        if(checkStatus[i].status == "3"||checkStatus[i].status == "4"){
            $('.disabledbutton').attr('disabled',false);
            $('.disabledbutton').css("background","#009688")
            return false;
        }
    }
    $('.disabledbutton').attr('disabled', true);
    $('.disabledbutton').css("background", "#b1b1b1");
});

let costBpmId = '';//流程实例id（当前审批流程的id）
let taskId='';//任务id
table.on('tool(maininformationtable)', function(obj){//注：tool是table模块的工具条事件。maininformationtable是table原始容器的属性 lay-filter="对应的值"
    var data = obj.data;//获得当前行数据
    if(obj.event === 'update') {//获得 lay-event 对应的值 obj.event
        if(obj.data.costType == "1"){
            parent.intab("views/jsp/Money/tpl/registerdirectchargesUpdate.jsp?costCode="+obj.data.code,"修改直接费用")
        }else{
            parent.intab("views/jsp/Money/tpl/registrationverheadexpensesUpdate.jsp?costCode="+obj.data.code,"修改间接费用")
        }
    }else if(obj.event === 'delectYes'){
        let costId=obj.data.id;
        layer.confirm('确定彻底删除么', function (index) {
            $.ajax({
                type:"POST",
                dataType:"json",
                contentType: 'application/json',
                data:JSON.stringify(costId),
                async:false,
                url:"cost/delCostByCostId",
                success:function(res) {
                    if (res.status == 200) {
                        obj.del();
                        layer.close(index);
                    }else {
                        layer.msg('删除失败');
                    }
                }
            });


        });
    }else if(obj.event === 'delete'){
        let req={};
        let costIds=new Array();
        costIds.push(obj.data.id);
        req['costIds']=costIds;
        req['status']=5;
        layer.confirm('确定删除么', function (index) {
            $.ajax({
                type:"POST",
                dataType:"json",
                contentType: 'application/json',
                data:JSON.stringify(req),
                async:false,
                url:"cost/updateCostTypeByCostId",
                success:function(res) {
                    if (res.status == 200) {
                        obj.del();
                        layer.close(index);
                    }else {
                        layer.msg('删除失败');
                    }
                }
            });


        });
    }else if(obj.event === 'submits'){
        // layer.confirm('确定提交审批吗', function (index) {
        //     costBpmId=startPurchaseProcess(obj.data.id);
        //     update(obj.data.id,2,'提交审批');
        //     taskId=getTasKId(costBpmId);
        //     commit(taskId);
        // });

        let req={};
        let costIds=new Array();
        costIds.push(obj.data.id);
        req['costIds']=costIds;
        req['status']=2;
        layer.confirm('确定提交审批吗', function (index) {
            layer.msg('提交审批');
            $.ajax({
                type:"POST",
                dataType:"json",
                contentType: 'application/json',
                data:JSON.stringify(req),
                async:false,
                url:"cost/updateCostTypeByCostId",
                success:function(res) {
                    if (res.status == 200) {
                        table.reload("maininformationtableid");
                        layer.msg('提交审批');
                    }else {
                        layer.msg('提交失败');
                    }
                }
            });

        });

    }else if(obj.event === 'through'){
        let req={};
        let costIds=new Array();
        costIds.push(obj.data.id);
        req['costIds']=costIds;
        req['status']=3;
        console.log(req);
        layer.confirm('确定审批通过吗', function (index) {
            $.ajax({
                type:"POST",
                dataType:"json",
                contentType: 'application/json',
                data:JSON.stringify(req),
                async:false,
                traditional:true,
                url:"cost/updateCostTypeByCostId",
                success:function(res) {
                    if (res.status == 200) {
                        table.reload("maininformationtableid");
                        layer.msg('审批通过');
                    }else {
                        layer.msg('审批通过失败');
                    }
                }
            });
        });
    }else if(obj.event === 'backtothe'){
        let req={};
        let costIds=new Array();
        costIds.push(obj.data.id);
        req['costIds']=costIds;
        req['status']=1;
        layer.confirm('确定审批退回吗', function (index) {
            $.ajax({
                type:"POST",
                dataType:"json",
                contentType: 'application/json',
                data:JSON.stringify(req),
                async:false,
                traditional:true,
                url:"cost/updateCostTypeByCostId",
                success:function(res) {
                    if (res.status == 200) {
                        table.reload("maininformationtableid");
                        layer.msg('审批退回');
                    }else {
                        layer.msg('退回失败');
                    }
                }
            });
        });
    }else if(obj.event === 'complete'){
        let req={};
        let costIds=new Array();
        costIds.push(obj.data.id);
        req['costIds']=costIds;
        req['status']=4;
        layer.confirm('确定完成吗', function (index) {
            $.ajax({
                type:"POST",
                dataType:"json",
                contentType: 'application/json',
                data:JSON.stringify(req),
                async:false,
                traditional:true,
                url:"cost/updateCostTypeByCostId",
                success:function(res) {
                    if (res.status == 200) {
                        table.reload("maininformationtableid");
                        layer.msg('完成');
                    }else {
                        layer.msg('完成失败');
                    }
                }
            });
        });
    }else if(obj.event === 'completeBacktothe'){
        let req={};
        let costIds=new Array();
        costIds.push(obj.data.id);
        req['costIds']=costIds;
        req['status']=3;
        layer.confirm('确定退回吗', function (index) {
            $.ajax({
                type:"POST",
                dataType:"json",
                contentType: 'application/json',
                data:JSON.stringify(req),
                async:false,
                traditional:true,
                url:"cost/updateCostTypeByCostId",
                success:function(res) {
                    if (res.status == 200) {
                        table.reload("maininformationtableid");
                        layer.msg('退回');
                    }else {
                        layer.msg('退回失败');
                    }
                }
            });
        });
    }else if(obj.event === 'reduction'){
        let id=obj.data.id
        layer.confirm('确定还原吗', function (index) {
            $.ajax({
                type:"POST",
                dataType:"json",
                contentType: 'application/json',
                data:JSON.stringify(id),
                async:false,
                url:"cost/updateCostStatusDustbinToDrafts",
                success:function(res) {
                    if (res.status == 200) {
                        table.reload("maininformationtableid");
                        layer.msg('还原');
                    }else {
                        layer.msg('还原失败');
                    }
                }
            });

        });
    }else if(obj.event === 'feepayment'){
        layer.open({
            type: 2,
            area: ['1488px', '800px'],
            content: 'views/jsp/Money/tpl/feepayment.jsp?costCode='+obj.data.code
        });
    }else if(obj.event === 'akeybreakupcost'){
        layer.open({
            type: 2,
            area: ['1488px', '800px'],
            content: 'views/jsp/Money/tpl/akeybreakupcost.jsp?costCode='+obj.data.code
        });
    }else if (obj.event === "registrationnumber"){
        parent.intab("views/jsp/Money/tpl/viewcost.jsp?costCode="+obj.data.code+"&costId="+obj.data.id,"查看费用明细")
    }
});
function req(data){
    let req=data.field;
    let op=req.operatorCode;
    if (isEmpty(op)){
        req.operatorCode=loginUserCode
    }
    return req
}
//字段是否为空或者零
function isEmpty(obj){
    if(typeof obj == "undefined" || obj == null || obj == "" || obj == 0){
        return true;
    }else{
        return false;
    }
}
//搜索提交
form.on('submit(submitform)', function(data){
    if (isEmpty(operationList.getValue('valueStr')) && isEmpty(deptOperationList.getValue('valueStr')) && isEmpty(salesmanList.getValue('valueStr')) && isEmpty(deptSalesmanList.getValue('valueStr'))){
        data.field.operationCode=user.code;
    }
    table.reload('maininformationtableid', {
        data:data1 ,
        page: {
            limit:50,
            curr: 1
        },
        where: data.field
    }, 'data');
    return false;
});

table.on('toolbar(maininformationtable)', function(obj){
    var checkStatus = table.checkStatus(obj.config.id);
    switch(obj.event){
        case 'registerdirectcharges':
            parent.intab("views/jsp/Money/tpl/registerdirectcharges.jsp","登记直接费用");
            break;
        case 'registrationoverheadexpenses':
            parent.intab("views/jsp/Money/tpl/registrationverheadexpenses.jsp","登记间接费用");
            break;
        case 'new':
            if(checkStatus.data.length > 1){
                layer.msg( "每次只能打印一个费用单据! ");
                break;
            }
            if(checkStatus.data.length == 0){
                layer.msg("请选择要打印的费用单据! ");
                break;
            }
            if(checkStatus.data[0].costType=="1"){
                window.open("views/jsp/report.jsp?ym=costDirectReport&code=code:"+checkStatus.data[0].code)
            }else if (checkStatus.data[0].costType=="2"){
                window.open("views/jsp/report.jsp?ym=costIndirectReport&code=code:"+checkStatus.data[0].code)
            }

            break;
        case 'dels':
            var data=checkStatus.data,delList=[];
            data.forEach(function(n,i){
                delList.push(n.id);
            });
            if(delList!=''){
                let req={};
                let costIds=new Array();
                req['costIds']=costIds;
                req['status']=5;
                layer.confirm('确定删除所选项吗？',function (index) {
                    let cbList = table.cache["maininformationtableid"];
                    for(let i = 0;i<cbList.length;i++){
                        delList.forEach((item, index) => {
                            //当数组中任意一个元素的rowIndex值与取消复选框的元素对象属性rowIndex的下标值相等，则在数组中删除该元素
                            if (typeof (cbList[i]) != "undefined"&&item == cbList[i].id) {
                                costIds.push(cbList[i].id);
                                cbList.splice(i, 1);
                            }
                        });
                    }
                    console.log(req);
                    $.ajax({
                        type:"POST",
                        dataType:"json",
                        contentType: 'application/json',
                        data:JSON.stringify(req),
                        async:false,
                        url:"cost/updateCostTypeByCostId",
                        traditional:true,
                        success:function(res) {
                            if (res.status == 200) {
                                table.reload("maininformationtableid");
                                layer.msg('删除成功');
                            }
                        }
                    });

                })
            }else{
                layer.msg('请选择需要删除的行');
            }
            break;
    };
});
$("#warehousingcostsharing").on("click",function () {
    let checkStatus = table.checkStatus("maininformationtableid").data;
    if (checkStatus.length == 0) {
        layer.msg("请选择数据")
        return false;
    }

    let code="";
    if (checkStatus.length != 0) {
        for (let i = 0; i < checkStatus.length; i++) {
            if (i == checkStatus.length - 1) {
                code += checkStatus[i].code;
            } else {
                code += checkStatus[i].code + ",";
            }
        }
    }
    layer.open({
        type: 2,
        area:["80%","95%"],
        content: 'views/jsp/Money/tpl/warehousingcostsharing.jsp?code='+code
    });
});
$("#akeybreakup").on("click",function () {
    layer.open({
        type: 2,
        area: ['1488px', '800px'],
        content: 'views/jsp/Money/tpl/akeybreakupcost.jsp'
    });
});
$("#statistical").on("click",function () {
    parent.intab("views/jsp/Money/tpl/statistics.jsp","费用统计")
});


//审批流开始，获取流程ID
function startPurchaseProcess(bid) {
    let res;
    $.ajax({
        type : 'get',
        data:{"processDefId":'cost',"bid":bid,"variables":null},
        url:'process/startProcess',
        dataType:"json",
        contentType: "application/x-www-form-urlencoded; charset=utf-8",
        async:false,
        success : function (da) {
            if(da.status==200 ){
                res=da.data;
            }
        },
        error: function(data) {
            // layer.msg("获取失败!");
        }
    });
    return res;
}
//boxStatus 1 草稿 2 待批  3:已批 4 完成 5 垃圾
//costBpmStatus审批状态  0：未审核 1：审批中 2：审核完成。提交审批设置初始状态为0
//更新费用的状态
function update(id,status,titleName) {
    let tf = false;
    let msgInfo = "";
    let dataJson = {
        "id":id,
        "status":status,
        "costBpmId":costBpmId,
        "costBpmStatus":"1",
    };
    $.ajax({
        type: 'POST',
        data: JSON.stringify(dataJson),
        url: 'cost/updateCostStatusByCostId',
        dataType: "json",
        contentType: 'application/json;charset=utf-8',
        async: false,
        success: function (da) {
            if (da.status == 200) {
                tf = true;
                msgInfo = titleName+"成功!"
                table.reload('maininformationtableid');
            }else{
                msgInfo = titleName+"失败!"
            }
        },
        error: function (data) {
            msgInfo = titleName+"异常!"
        }
    });
    layer.msg(msgInfo);
    return tf;
}
//根据流程ID获取任务ID
function getTasKId(instanceId) {
    let res;
    $.ajax({
        type:"POST",
        dataType:"json",
        contentType: 'application/json',
        data:instanceId,
        async:false,
        url:"cost/getTasKId",
        success : function (da) {
            if(da.status==200 ){
                res=da.data;
            }
        },
        error: function(data) {
            // layer.msg("获取失败!");
        }
    });
    return res;
}
//第一次提交时自动通过，直接到下一个审批人节点
function commit(taskId) {
    $.ajax({
        type : 'get'
        ,data:{"taskId":taskId,"variables":null,"activityId":null,"comment":null},
        url:'cost/commitProcess',
        dataType:"json",
        async:false,
        success : function (da) {
            if(da.status==200 ){
                layer.msg("提交成功");
                close();
            }else{
                layer.msg("提交失败!");
            }
        },
        error: function(data) {
            // layer.msg("获取失败!");
        }
    });

}
//判断当前登录用户是否有 工厂统计及费用方式 权限
function factory_statistics_cost(){
    $.ajax({
        url:'shipmentPlan/factoryStatisticsCost',
        async:false,
        success : function (da) {
            if(da.status==200 ){
                factoryStatisticsCost=da.data;
            }
        }
    });
}
